import 'dart:developer';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/pay/pay_bottom_logic.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/entity/pay/recharge_entity.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/base/qkd_bottomsheet.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import '../entity/pay/usable_coupon.dart';
import '../resources/colours.dart';
import '../utils/constant.dart';
import '../utils/routes.dart';
import 'base/qkd_text.dart';
import 'base/qkd_button.dart';
import 'coupon_bottom_sheet.dart';

enum PayScene {
  recharge(type: 0),
  expert(type: 1),
  subs(type: 2),
  ai(type: 3),
  aiSingle(type: 3),
  vip(type: 4),
  secret(type: 5),
  planForm(type: 6),
  aiPack(type: 7),
  couponPack(type: 8),
  planPack(type: 9);

  final int type;

  const PayScene({required this.type});
}

class PayMode {
  String? logo;
  String? name;
  int? type;

  PayMode({this.logo, this.name, this.type});

  PayMode.fromResource(ResourceEntity? entity) {
    try {
      logo = entity?.imgUrl;
      name = entity?.title;
      type = entity?.content?.toInt();
    } catch (e) {
      log(e.toString());
    }
  }
}

extension PayModeCheck on PayMode {
  bool get goAlipay {
    return type == 21;
  }

  bool get goWechat {
    return type == 22;
  }

  bool get goWeb {
    return type == 302 || type == 301;
  }
}

class PayBottomSheet extends StatelessWidget {
  PayBottomSheet({super.key, required this.payInfo, this.description})
      : recharge = false;
  PayBottomSheet.recharge(
      {super.key, required String price, required this.gold, this.description})
      : recharge = true,
        payInfo = PayInfo(price: price, payScene: PayScene.recharge, buyId: "");

  final PayInfo payInfo;
  final tag = math.Random.secure().nextDouble() * 10000;
  late final logic = Get.put(PayBottomLogic(), tag: "$tag");
  late final bool recharge;
  late final double gold;
  final String? description;

  static Future<PayResult?> show({required PayInfo payInfo}) async {
    return await Get.bottomSheet(
        isScrollControlled: true, PayBottomSheet(payInfo: payInfo));
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PayBottomLogic>(
        tag: "$tag",
        initState: (state) {
          logic.payInfo = payInfo;
        },
        builder: (logic) {
          return QkdBottomSheet(
              closeResult:
                  recharge ? null : const PayResult(toPay: PayStatus.failed),
              child: Column(mainAxisSize: MainAxisSize.min, children: [
                QkdText(
                  "确认${recharge ? "充值" : "支付"}",
                  fontSize: 16,
                ),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    QkdText(logic.priceReal.toStringAsFixed(2),
                        fontSize: 36, fontWeight: FontWeight.w500),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 7),
                      child: QkdText(' 球币'.changeUnit,
                          fontSize: 20, fontWeight: FontWeight.w500),
                    ),
                  ],
                ),
                if (logic.price != logic.priceReal)
                  QkdText("${logic.price.toStringAsFixed(2)}球币".changeUnit,
                      fontSize: 12,
                      color: Colours.grey99,
                      decoration: TextDecoration.lineThrough),
                if (recharge)
                  QkdText(
                    description ?? '',
                    fontSize: 12,
                    color: Colours.main,
                  ),
                Container(height: 20),
                group(list: [
                  if (recharge)
                    ...logic.payList
                            ?.map((e) => checkLine(payMode: e))
                            .toList() ??
                        []
                  else ...[
                    if (logic.payInfo.payScene.type != 7 &&
                        logic.payInfo.payScene.type != 8)
                      couponInfo(),
                    if (logic.payToBuy) ...[goldInfo(), payModeInfo()]
                  ]
                ]),
                const SizedBox(height: 10),
                QkdButton(
                  onPressed: () async {
                    if (logic.click) {
                      logic.click = false;
                      if (recharge) {
                        Utils.onEvent(logic.payMode == 1 ? "zfbzf" : "vxzf");
                        Get.back(result: logic.payMode);
                      } else {
                        await logic.pay();
                      }
                    }
                  },
                  text: "确认支付",
                  foregroundColor: Colors.white,
                  backgroundColor: Colours.main,
                  width: Get.width,
                  borderRadius: 4,
                  textStyle: const TextStyle(fontWeight: FontWeight.w500),
                ).marginOnly(top: 35),
                Container(
                  height: 44,
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const QkdText(
                        "支付即代表您已同意",
                        fontSize: 12,
                        color: Colours.grey99,
                        needCenter: true,
                      ),
                      QkdButton(
                        onPressed: () {
                          Get.toNamed(Routes.webview,
                              arguments: {"url": Constant.payPolicyUrl});
                        },
                        text: "《用户充值协议》",
                        strutStyle: Styles.centerStyle(fontSize: 18),
                        textStyle: const TextStyle(fontSize: 12),
                      ),
                      if (logic.payInfo.payScene == 4) ...[
                        const QkdText(
                          "、",
                          fontSize: 12,
                          color: Colours.grey99,
                          needCenter: true,
                        ),
                        QkdButton(
                          onPressed: () {
                            Get.toNamed(Routes.webview,
                                arguments: {"url": Constant.vipPolicyUrl});
                          },
                          text: "《球客岛会员服务协议》",
                          strutStyle: Styles.centerStyle(fontSize: 18),
                          textStyle: const TextStyle(fontSize: 12),
                        )
                      ]
                    ],
                  ).marginOnly(bottom: 10),
                ),
              ]));
        });
  }

  Widget goldInfo() {
    return infoLine(needArrow: false, name: "球币余额", value: [
      QkdText(
          "${logic.gold.toStringAsFixed(2)}球币(需充值${logic.needPay.toStringAsFixed(2)})")
    ]);
  }

  Widget payModeInfo() {
    return infoLine(name: "支付方式", value: [QkdText(logic.payMode?.name)])
        .tap(() {
      Get.bottomSheet(
        QkdBottomSheet(
            title: "选择支付方式",
            backIcon: "arrow_back.png",
            child: SizedBox(
              height: 461 + 5,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  group(
                          list: logic.payList
                                  ?.map((e) =>
                                      checkLine(payMode: e, isSheet: true))
                                  .toList() ??
                              [])
                      .paddingOnly(top: 26, bottom: 40),
                ],
              ),
            )),
        isScrollControlled: true,
        isDismissible: false,
        barrierColor: Colors.transparent,
      );
    });
  }

  Widget couponInfo() {
    List<Widget> list = [const QkdText("不使用优惠券")];
    if (logic.usable == 0) {
      list = [const QkdText("暂无可用")];
    } else if (logic.select != null) {
      list = [
        Container(
            padding: const EdgeInsets.symmetric(horizontal: 2),
            height: 14,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: Colours.main, borderRadius: BorderRadius.circular(3)),
            child: QkdText(
              "${logic.select?.typeUpper ?? ""}${logic.select?.typeLower ?? ""}",
              color: Colors.white,
              fontSize: 10,
              needCenter: true,
            )).marginOnly(right: 2.5),
        QkdText("-${logic.select?.gold?.toStringAsFixed(2)}球币".changeUnit,
            color: Colours.main, height: 1.4),
      ];
    }
    return infoLine(logo: "my_discount_wallet.png", name: "优惠券", value: list)
        .tap(() async {
      log("selected = ${logic.select}");
      final result = await Get.bottomSheet(
        CouponBottomSheet(
            coupons: logic.payInfo.coupons ?? [], selected: logic.select),
        isDismissible: false,
        isScrollControlled: true,
        barrierColor: Colors.transparent,
      );
      if (result is UsableCouponEntity) {
        logic.select = result;
      } else if (result == false) {
        logic.select = null;
      }
    });
  }

  Widget infoLine(
      {String? logo,
      required String name,
      required List<Widget> value,
      bool needArrow = true}) {
    return Container(
      height: 52,
      padding: const EdgeInsets.symmetric(horizontal: 14),
      alignment: Alignment.center,
      child: DefaultTextStyle(
        style: const TextStyle(fontSize: 14, color: Colours.grey99),
        child: Row(
          children: [
            // if(logo != null)
            // Image.asset(width: 22, Utils.getImgPath(logo)).paddingOnly(right: 6),
            QkdText(name, color: Colours.text292D32),
            const Spacer(),
            ...value,
            if (needArrow) ...[
              const SizedBox(width: 6),
              Image.asset(width: 6, Utils.getImgPath("arrow_right.png"))
            ]
          ],
        ),
      ),
    );
  }

  Widget checkLine(
      {required PayMode payMode,
      bool isSheet = false,
      ValueChanged<PayMode>? onTap}) {
    return GetBuilder<PayBottomLogic>(
      tag: "$tag",
      init: PayBottomLogic(),
      builder: (logic) => Container(
          height: 52,
          padding: const EdgeInsets.symmetric(horizontal: 14),
          alignment: Alignment.center,
          child: Row(
            children: [
              if (payMode.logo.hasValue)
                QkdImage(imageUrl: payMode.logo, width: 22, height: 22)
                    .paddingOnly(right: 10),
              QkdText(payMode.name, color: Colours.text292D32),
              const Spacer(),
              Image.asset(
                  width: 24,
                  height: 24,
                  Utils.getImgPath(
                      logic.payMode == payMode ? 'check.png' : 'uncheck.png'))
            ],
          ).tap(() {
            logic.payMode = payMode;
            onTap?.call(payMode);
            if (isSheet) Get.back();
          })),
    );
  }

  Widget group({required List<Widget> list}) {
    return Container(
      decoration: BoxDecoration(
          color: Colours.greyF5F7FA, borderRadius: BorderRadius.circular(3)),
      child: Column(
          mainAxisSize: MainAxisSize.min,
          children: list.insertEvery(
              const Divider(color: Colours.greyEE, height: 0.5)
                  .paddingSymmetric(horizontal: 23))),
    );
  }
}
